package com.reactim.user.repository;

import com.reactim.user.entity.FriendRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 好友请求Repository
 */
@Repository
public interface FriendRequestRepository extends JpaRepository<FriendRequest, Long> {
    
    /**
     * 查找用户收到的好友请求
     */
    Page<FriendRequest> findByToUserIdAndStatusOrderByCreatedAtDesc(
            Long toUserId, FriendRequest.RequestStatus status, Pageable pageable);
    
    /**
     * 查找用户发送的好友请求
     */
    Page<FriendRequest> findByFromUserIdAndStatusOrderByCreatedAtDesc(
            Long fromUserId, FriendRequest.RequestStatus status, Pageable pageable);
    
    /**
     * 查找两个用户之间的好友请求
     */
    Optional<FriendRequest> findByFromUserIdAndToUserId(Long fromUserId, Long toUserId);
    
    /**
     * 查找两个用户之间的待处理请求
     */
    Optional<FriendRequest> findByFromUserIdAndToUserIdAndStatus(
            Long fromUserId, Long toUserId, FriendRequest.RequestStatus status);
    
    /**
     * 统计用户收到的待处理请求数量
     */
    long countByToUserIdAndStatus(Long toUserId, FriendRequest.RequestStatus status);
    
    /**
     * 查找过期的请求
     */
    List<FriendRequest> findByStatusAndExpiredAtBefore(
            FriendRequest.RequestStatus status, LocalDateTime expiredAt);
    
    /**
     * 批量更新过期请求状态
     */
    @Modifying
    @Query("UPDATE FriendRequest fr SET fr.status = :newStatus, fr.updatedAt = :now " +
           "WHERE fr.status = :oldStatus AND fr.expiredAt < :expiredAt")
    int updateExpiredRequests(@Param("oldStatus") FriendRequest.RequestStatus oldStatus,
                             @Param("newStatus") FriendRequest.RequestStatus newStatus,
                             @Param("expiredAt") LocalDateTime expiredAt,
                             @Param("now") LocalDateTime now);
    
    /**
     * 删除指定时间之前的已处理请求
     */
    @Modifying
    @Query("DELETE FROM FriendRequest fr WHERE fr.status IN :statuses AND fr.updatedAt < :beforeDate")
    int deleteProcessedRequestsBefore(@Param("statuses") List<FriendRequest.RequestStatus> statuses,
                                     @Param("beforeDate") LocalDateTime beforeDate);
}